package com.example.imagesteganographylibrary.Utils;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class Crypto {
    private static HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP,0x001,"Crypto");
    private static String aesKeys = "AES";

    /**
     * encryptMessage
     *
     * @param message String
     * @param secret_key String
     * @return Encrypted Message {String}
     */
    public static String encryptMessage(String message, String secret_key) {
        // Creating key and cipher
        SecretKeySpec aesKey = new SecretKeySpec(secret_key.getBytes(), "AES");
        Cipher cipher;
        byte[] encrypted = new byte[0];
        //AES cipher
        try {
            cipher = Cipher.getInstance(aesKeys);
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            encrypted = cipher.doFinal(message.getBytes());
        } catch (Exception e) {
            HiLog.error(logLabel,e.getMessage());
        }

        return Base64.getUrlEncoder().encodeToString(encrypted);
    }

    /**
     * decryptMessage
     *
     * @param secret_key secret_key
     * @param encrypted_message encrypted_message
     * @return Message {String}
     */
    public static String decryptMessage(String encrypted_message, String secret_key) {
        SecretKeySpec aesKey = new SecretKeySpec(secret_key.getBytes(), "AES");
        Cipher cipher;
        String decrypted = "";
        byte[] decoded;

        // decrypting the text
        try {
            //AES cipher
            cipher = Cipher.getInstance(aesKeys);
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            decoded = Base64.getUrlDecoder().decode(encrypted_message.getBytes());
            decrypted = new String(cipher.doFinal(decoded));
        } catch (Exception e) {
            HiLog.error(logLabel,e.getMessage());
        }

        return decrypted;
    }
}
